package br.com.agiledev.webscrum.manager;

import java.util.ArrayList;

import javax.persistence.EntityManager;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import br.com.agiledev.webscrum.entity.Item;
import br.com.agiledev.webscrum.entity.ItemProduct;
import br.com.agiledev.webscrum.entity.ItemRelease;
import br.com.agiledev.webscrum.entity.ItemSprint;
import br.com.agiledev.webscrum.entity.Product;
import br.com.agiledev.webscrum.entity.Release;
import br.com.agiledev.webscrum.entity.Sprint;

@Name("itemManager")
@Scope(ScopeType.APPLICATION)
@AutoCreate
public class ItemManager {

    @In
    EntityManager entityManager;

    public ItemProduct associate(Item item, Product product) {

	ItemProduct ip = new ItemProduct(item, product);

	entityManager.persist(ip);

	if (product.getItens() == null) {
	    product.setItens(new ArrayList<ItemProduct>());
	}

	product.getItens().add(ip);

	return ip;
    }

    public ItemRelease associate(Item item, Release release) {

	ItemRelease ir = new ItemRelease(item, release);

	entityManager.persist(ir);

	if (release.getItens() == null) {
	    release.setItens(new ArrayList<ItemRelease>());
	}

	release.getItens().add(ir);

	return ir;
    }

    public ItemSprint associate(Item item, Sprint sprint) {

	ItemSprint is = new ItemSprint(item, sprint);

	entityManager.persist(is);

	if (sprint.getItens() == null) {
	    sprint.setItens(new ArrayList<ItemSprint>());
	}

	sprint.getItens().add(is);

	return is;
    }
    
    public void desAssociate(Item item, Product product) {
	
	product.removeItem(item);
	
	entityManager.createNamedQuery("ItemProduct.excluirPorItem").setParameter("item", item).executeUpdate();
	entityManager.createNamedQuery("ItemRelease.excluirPorItem").setParameter("item", item).executeUpdate();
	entityManager.createNamedQuery("ItemSprint.excluirPorItem").setParameter("item", item).executeUpdate();

	entityManager.remove(item);
    }
    
    public void desAssociateRelease(Item item) {
	entityManager.createNamedQuery("ItemRelease.excluirPorItem").setParameter("item", item).executeUpdate();
	entityManager.createNamedQuery("ItemSprint.excluirPorItem").setParameter("item", item).executeUpdate();
    }
    
    public void desAssociateSprint(Item item) {
	entityManager.createNamedQuery("ItemSprint.excluirPorItem").setParameter("item", item).executeUpdate();
    }    
}